import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import Skeleton from 'taro-skeleton'
import {View, Image, ScrollView, Block} from '@tarojs/components'
import {connect} from 'react-redux'
import {
  CityLocation as CityLocationType,
  TouristLineIndexPageData,
  Good
} from '../../utils/server.interface'
import {platform} from '../../utils/platform-settting.service'
import {http} from '../../utils/http'
import {
  IDENTITY_IS_SELLER,
  LIST_CATEGORY,
  RESOURCE_URL,
  SCAN_BIND_SELLER,
  TARO_ENV,
  UPDATE_USER_SHARE_DATE
} from '../../constants/api'
import fetchNewGoodsList from "../../utils/fetchNewGoodsList";
import Headerbar from '../components/header-bar/header-bar'
import MainMenu from '../../components/main-menu/main-menu'
import CityLocation from '../../components/city-location/city-location'
import SmallGoodsBox from '../../components/small-goods-box/small-goods-box'
import {getHeadTop, gotoPage, vcmonitor, clearSearch} from '../../utils/tools'
import {user} from '../../utils/user.service'
import SupportBar from '../../components/support-bar/support-bar'
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import Share from "../../components/share/share";
import AdvertisementMember from "../../components/advertisement/member";
import {getMemberAdvertisement} from "../../utils/getCommonData";
import './index.scss'

type PageStateProps = {
  location: CityLocationType
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  systemInfo?: any
  depth: number
  isAll: boolean
  isActive: boolean
  categoryIdOld: number
  linkUri: string
  searchText: string
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  goods: Good[]
  categoryId: number
  subCategory: any
  memberAdvertisement: any
  subCategoryConvert: any
  pageData: any
  headTop: any
  showLeftIcon: boolean
  isUser: boolean
  showLoading: boolean
  headTopAll: number
  scrollTop: number
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Index {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({}))

class Index extends Component {
  state: PageState = {
    systemInfo: {},
    isActive: true,
    categoryIdOld: 0,
    depth: 0,
    linkUri: '',
    memberAdvertisement: '',
    searchText: '',
    loadMoreStatus: 'loading',
    goods: [],
    categoryId: 0,
    subCategory: [],
    subCategoryConvert: [],
    pageData: {
      headBg: "https://resource.ivcheng.com/resources/system/img/tourist-line.jpg",
      pageTitle: "景点详情",
      menus: [],
      hots: []
    },
    headTop: {
      statusBar: 0,
      top: 0,
    },
    showLeftIcon: true,
    isUser: true,
    showLoading: true,
    headTopAll: 0,
    scrollTop: 0
  }
  page = 1
  shareParams = ''

  async UNSAFE_componentWillMount() {
    vcmonitor(this)
    const categoryId = Taro.getCurrentInstance().router.params.category || 0
    const pageData = await http.get<TouristLineIndexPageData>('api/v3/custom/toursline', {})
    if (!pageData) {
      return false
    }
    const headTop: any = getHeadTop()
    this.setState({
      showLeftIcon: process.env.P_ENV !== 'kontai',
      categoryId,
      pageData,
      showLoading: false,
      headTop,
      headTopAll: headTop.statusBar + headTop.top
    })
  }

  async componentDidShow() {
    clearSearch()
    Taro.getSystemInfo({
      success: (res) => {
        this.setState({systemInfo: res})
      }
    })
    const categoryId = Taro.getCurrentInstance().router.params.category || 0
    this.setState({categoryIdOld: categoryId, memberAdvertisement: await getMemberAdvertisement({ position: 'xianlu' })})
    const goods = await this.getGoods(this.page, categoryId)
    const categoryData = (await http.HGet(LIST_CATEGORY, {type: 2, c: categoryId})) || {}
    if (categoryData.data.some((item) => item.id === categoryId)) {
      this.setState({isActive: false})
    }
    if (categoryData.data.length > 0) {
      this.setState({depth: categoryData.data[0].depth})
    }
    this.setState({
      goods,
      subCategory: categoryData.data,
      subCategoryConvert: categoryData.data.map(item => ({
        name: item.name,
        id: item.id,
        url: item.link,
        urlType: item.link_type,
        depth: item.depth
      })),
      isAll: categoryData.is_all
    })
    this.shareParams = await user.getSellerParams()
    let link = '/common/tourist-line/index?' + this.shareParams
    if (process.env.TARO_ENV === 'h5') {
      link = window.location.origin + link
      const shareData = {
        title: platform.info.platformName,
        desc: '旅游线路',
        link,
        imgUrl: platform.info.platformLogo
      }
      h5Wx.share(shareData)
    } else {
      link += `&sKey=${Taro.getStorageSync('sKey' || '')}`
    }
    if (this.state.pageData.pageTitle) {
      await Taro.setNavigationBarTitle({
        title: this.state.pageData.pageTitle
      })
    }
    let isUser = true
    if (process.env.DISTINGUISH_IDENTITY) {
      const identityIsSeller = await http.get(IDENTITY_IS_SELLER, {})
      isUser = !identityIsSeller.isSeller
    }
    this.setState({linkUri: link, isUser})
    const bindSellerIds = Taro.getCurrentInstance().router.params.bindSellerId || ''
    const tempSellerIds = Taro.getCurrentInstance().router.params.tempSellerId || ''
    if ((bindSellerIds || tempSellerIds) && process.env.DISTINGUISH_IDENTITY) {
      http.HPost(SCAN_BIND_SELLER, {temp_seller_id: tempSellerIds, refer_seller_id: bindSellerIds});
    }
  }

  onShareAppMessage() {
    if (process.env.TARO_ENV !== 'tt') {
      http.post(UPDATE_USER_SHARE_DATE, {})
    }
    return {
      title: platform.info.platformName,
      path: this.state.linkUri
    }
  }

  onShareTimeline() {
    if (process.env.TARO_ENV !== 'tt') {
      http.post(UPDATE_USER_SHARE_DATE, {})
    }
    return {
      title: platform.info.platformName,
      query: this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`,
    }
  }

  async getGoods(page = 1, categoryId) {
    // 商品列表
    const goodsData = await fetchNewGoodsList.getGoodsList({
      module_type: "4",
      data_type: "4",
      page: page,
      length: 10,
      key_word: this.state.searchText,
      // region_region: this.props.location.region_id,
      region_region: "",
      region_category: categoryId === 0 ? "" : categoryId,
    });
    if (goodsData && Array.isArray(goodsData)) {
      if (goodsData.length < 10) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      return goodsData
    } else {
      this.setState({loadMoreStatus: 'noMore'})
      return []
    }
  }

  async searchClick() {
    this.page = 1
    this.setState({loadMoreStatus: 'loading', goods: []}, async () => {
      const goods = await this.getGoods(this.page, this.state.categoryId)
      this.setState({goods})
    })
  }

  searchClear() {
    this.page = 1
    this.setState({searchText: '', loadMoreStatus: 'loading', goods: []}, async () => {
      const goods = await this.getGoods(this.page, this.state.categoryId)
      this.setState({goods})
    })
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.goods
      this.page++
      const newData = await this.getGoods(this.page, this.state.categoryId)
      this.setState({goods: [...old, ...newData]})
    }
  }

  inputChange(value) {
    this.setState({searchText: value})
  }

  async subCategoryClick(id, depth) {
    Taro.showLoading({title: '加载中...'})
    this.page = 1
    let data
    if (depth === 0) { // 全部
      if (this.state.depth === 2) { // 三级
        // 没有下级
        const goods = await this.getGoods(this.page, this.state.categoryIdOld)
        this.setState({goods, isActive: true, categoryId: this.state.categoryIdOld})
      } else if (this.state.depth === 1) { // 有下级
        this.setState({isActive: true, categoryId: 0, goods: []})
        data = (await http.HGet(LIST_CATEGORY, {c: id, type: 2, category: 0, depth})) || {}
        if (data.data.length > 0) {
          const goods = await this.getGoods(this.page, this.state.categoryIdOld)
          if (goods.length > 0) {
            this.setState({
              goods, isAll: data.is_all, subCategory: data.data, subCategoryConvert: data.data.map(item => ({
                name: item.name, id: item.id, url: item.link, urlType: item.link_type,
                depth: item.depth
              }))
            })
          }
        }
      }
    } else {
      if (depth === 2) { // 没有下架
        const goods = await this.getGoods(this.page, id)
        this.setState({isActive: false, goods, categoryId: id})
      } else { // 有下级
        data = await http.HGet(LIST_CATEGORY, {c: id, type: 2, depth})
        if (data && data.data.length > 0) {
          this.setState({goods: [], categoryId: id, isActive: false})
          const goods = await this.getGoods(this.page, id)
          if (goods.length > 0) {
            if (data.data[0].id !== this.state.subCategory[0].id) {
              this.setState({
                categoryId: 0,
                isActive: true,
                isAll: data.is_all,
                subCategory: data.data,
                subCategoryConvert: data.data.map(item => ({
                  name: item.name, id: item.id, url: item.link, urlType: item.link_type,
                  depth: item.depth
                }))
              })
            }
            this.setState({goods})
          }
        }
      }
    }
    Taro.hideLoading()
  }

  onPageScroll(page) {
    this.setState({scrollTop: page.scrollTop})
  }

  render() {
    const {
      showLeftIcon,
      isUser,
      linkUri,
      goods,
      headTopAll,
      categoryId,
      pageData,
      headTop,
      showLoading,
      isAll,
      isActive,
      systemInfo,
      scrollTop,
      memberAdvertisement,
      subCategoryConvert
    } = this.state
    const offSetTop = scrollTop > 100 ? 100 : scrollTop
    const xAxis = 50 - offSetTop / 3.8
    const top = headTopAll + 40 - offSetTop / 2.5
    const maxWidth = systemInfo.screenWidth - 20
    const width = maxWidth - (offSetTop + offSetTop * 0.2)
    const smallBar = headTop.statusBar > 20 ? headTopAll + 88 : headTopAll + 98
    return (
      <View className='tourist-root' id='root'>
        <View>
          <GzhAuth />
          <Skeleton title className='paddingNone' loading={showLoading} titleWidth='100%' rowHeight='150px'>
            <Block>
              {(TARO_ENV !== 'h5' && TARO_ENV !== 'tt') &&
                <View className='header-bar' style={`width: ${offSetTop > 80 ? 'inherit' : '100%'};`}><Headerbar
                  showLeftIcon={showLeftIcon} opacity={offSetTop > 40 ? 0 : 1} title={pageData.pageTitle}
                /></View>}
              <View className='head'>
                <View className='search-bar'
                      style={`opacity: ${scrollTop >= 100 ? 1 : 0};left: ${(TARO_ENV === 'h5' || TARO_ENV === 'tt') ? '50' : xAxis}%;transform: translateX(-${(TARO_ENV === 'h5' || TARO_ENV === 'tt') ? '50' : xAxis}%);width: ${(TARO_ENV === 'h5' || TARO_ENV === 'tt') ? maxWidth : width}px;max-width: ${maxWidth}px;top: ${top}px;`}
                >
                  {(scrollTop >= 100) && <CityLocation />}
                </View>
              </View>
              <View className='head-back-img'><Image className='img' src={pageData.headBg} mode='widthFix' /></View>
              <View className='head-bg'
                    style={`height:${headTopAll + 45}px;background: rgba(242,242,242,${Math.min(offSetTop / 100, 1)});`}
              />
            </Block>
          </Skeleton>
          <Skeleton title className='paddingNone' loading={showLoading} titleWidth='100%' rowHeight='300px'>
            <Block>
              <View className='zoom' style='margin-top: 10px;'>
                <View className='categorys'>
                  {pageData.menus && pageData.menus.length > 0 && <MainMenu data={pageData.menus} />}
                </View>
                {pageData.hots && pageData.hots.length > 0 && <View className='hot'>
                  <View className='title'>热门目的地</View>
                  <View className='content-box'>
                    {pageData.hots.length > 0 && pageData.hots.map(item => <View className='item' key={item.id}
                                                                                 onClick={() => gotoPage(item.url)}
                    >
                      <Image mode='aspectFill' src={item.img} className='img' />
                      <View className='name'>{item.name}</View>
                    </View>)}
                  </View>
                </View>}
                {(process.env.P_ENV === 'vc' || process.env.P_ENV === 'kunxin') && !!platform.info && !!platform.info.applicationOpenVip && memberAdvertisement && <View style='margin: 0 10px;'>
                  <AdvertisementMember url={memberAdvertisement} />
                </View>}
                <View className='bottom-nav' style={`top: ${smallBar}px;`}>
                  <View className='main'>精挑细选</View>
                  <ScrollView scrollX enable-flex className='subNav'>
                    <View className='nav-box'>
                      {isAll && <View key={0} onClick={this.subCategoryClick.bind(this, 0, 0)}
                                      className={`nav-item ${isActive ? 'active' : ''}`}
                      >全部</View>}
                      {subCategoryConvert.length > 0 && subCategoryConvert.map(item =>
                        <View key={item.id} onClick={this.subCategoryClick.bind(this, item.id, item.depth)}
                              className={`nav-item ${categoryId === item.id ? 'active' : ''}`}
                        >{item.name}</View>
                      )}
                    </View>
                  </ScrollView>
                </View>
                <View className='bottom-goods'>
                  <SmallGoodsBox data={goods} />
                  {goods && goods.length == 0 &&
                    <View className='listNull'>
                      <Image src={`${RESOURCE_URL}/resources/images/shopnull.png`} mode='widthFix' />
                      <View className='text'>什么都没有,去看看别的吧~</View>
                    </View>
                  }
                </View>
              </View>
            </Block>
          </Skeleton>
          <Skeleton title loading={showLoading} titleWidth='100%' rowHeight='150px'>
            <Block>
              {linkUri && process.env.P_ENV !== 'lx' && <Share isUser={isUser} linkUri={linkUri} />}
            </Block>
          </Skeleton>
        </View>
        <SupportBar />
      </View>
    )
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>
